package com.zhuiYun.project.config;

import com.zhuiYun.project.config.jwt.ExceptionHandlerFilter;
import com.zhuiYun.project.config.jwt.JWTAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

import static org.springframework.security.config.Customizer.withDefaults;

/**
 * @ClassName WebSecurityConfig
 * @Description Security 权限配置
 * @Author zcy
 * @Date 2023/3/27 10:28
 **/
@Configuration
public class WebSecurityConfig{

    /**
     * 自定义用户登录实现类
     */
    @Autowired
    UserDetailsService userDetailsService;
    /**
     * 自定登录失败做出的返回结果
     */
    @Autowired
    AuthenticationEntryPoint authExceptionEntryPoint;
    /**
     * 自定义登出处理逻辑
     */
    @Autowired
    LogoutSuccessHandler logoutSuccessHandler;
    /**
     * 登录失败处理逻辑
     */
    @Autowired
    AuthenticationFailureHandler authenticationFailureHandler;
    /**
     *  登录成功的操作
     */
    @Autowired
    AuthenticationSuccessHandler authenticationSuccessHandler;
    /**
     * 捕获token异常
     */
    @Autowired
    ExceptionHandlerFilter exceptionHandlerFilter;

    /**
     * 声明密码加密方式
     * @return
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 放行路径
     */
    private  static  final  String[]  AUTH_WHITELIST  =  {
            // -- swagger ui
            "/swagger-resources/**",
            "/swagger-ui.html",
            "/swagger-ui/",
            "/v3/api-docs",
            "/v2/api-docs",
            "/swagger-ui/**",
            "/webjars/**",
            "/images/**",
            "/js/**",
            "/login",
            "/webjars/**",
            "/druid/**",
            "/DynamicAudit/DynamicAuditList",
            "/druid/**",
            "/show/**",
            "/DynamicState/**"

    };
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeHttpRequests((auth) -> {
                            try {
                                auth.antMatchers(AUTH_WHITELIST).permitAll()
                                        .anyRequest().authenticated()
                                        //异常处理(权限拒绝、登录失效等)
                                        .and().exceptionHandling().
                                            authenticationEntryPoint(authExceptionEntryPoint)//匿名用户访问无权限资源时的异常处理
                                        //登入
                                        .and().formLogin()
                                        .usernameParameter("loginName")
                                        .passwordParameter("password")
                                        .loginProcessingUrl("/login").
                                            permitAll().
                                            failureHandler(authenticationFailureHandler).//登录失败处理逻辑
                                            successHandler(authenticationSuccessHandler) //登录成功处理逻辑
                                        // 登出
                                        .and().logout().
                                            permitAll().
                                            logoutSuccessHandler(logoutSuccessHandler) //登出成功处理逻辑
                                        .and().sessionManagement().
                                            sessionCreationPolicy(SessionCreationPolicy.STATELESS)//禁用session
                                        .and().cors().configurationSource(configurationSource());
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        }
                )
                .httpBasic(withDefaults());
        // 禁用缓存
        http.headers().cacheControl();
        // 添加JWT过滤器
        http.addFilter(new JWTAuthenticationTokenFilter(authenticationManager(http)));
        // 注册异常捕获过滤器
        http.addFilterBefore(exceptionHandlerFilter, CorsFilter.class);
       return http.build();
    }

    /**
     * 注册自定义登录
     * @param httpSecurity
     * @return
     * @throws Exception
     */
    @Bean
    AuthenticationManager authenticationManager(HttpSecurity httpSecurity) throws Exception {
        AuthenticationManager authenticationManager = httpSecurity.getSharedObject(AuthenticationManagerBuilder.class)
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder())
                .and()
                .build();
        return authenticationManager;
    }

    CorsConfigurationSource configurationSource() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
        corsConfiguration.setAllowedMethods(Arrays.asList("*"));
        corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
        corsConfiguration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return source;
    }


}
